import random

WIDTH = 600
HEIGHT = 400

clr_list = [
    ["r", 5, (200, 0, 0)],
    ["g", 3, (0, 200, 0)],
    ["b", 1, (0, 0, 200)]
]

unit = 50

BACK_COLOR = (0, 0, 0)

def GetRandomColor():
    global clr_list
    return clr_list[random.randint(0, 2)]

class MyRect:
    def __init__(self, mid_x, mid_y, clr):
        self.mid_x = mid_x
        self.mid_y = mid_y
        self.clr = clr

    def GetGridPos(self):
        gx = self.mid_x // unit 
        gy = self.mid_y // unit

        return gx, gy

    def IsMe(self, gx, gy):
        rcgx, rcgy = self.GetGridPos()
        if rcgx == gx and rcgy == gy:
            return True
        
        return False

    def GetScore(self):
        return self.clr[1]

    def Draw(self):
        rc = Rect((self.mid_x - unit // 2, self.mid_y - unit // 2), (unit, unit))
        screen.draw.filled_rect(rc, self.clr[2])

rc_list = []

def Init():
    for r in range(0, 8):
        for c in range(0, 8):
            clr = GetRandomColor()
            rc = MyRect(r * unit + unit // 2, c * unit + unit // 2, clr)
            rc_list.append(rc)

Init()

PlayerScore = 0
AIScore = 0

GameOver = False

Result = ""

def AIBadPlay():
    global AIScore
    rc_index = random.randint(0, len(rc_list) - 1)
    AIScore += rc_list[rc_index].GetScore()
    del rc_list[rc_index]

def AIGoodPlay():
    global AIScore
    bestRC = rc_list[0]
    for i in range(1, len(rc_list)):
        if rc_list[i].GetScore() > bestRC.GetScore():
            bestRC = rc_list[i]

    AIScore += bestRC.GetScore()
    rc_list.remove(bestRC)

def AIPlay():
    global GameOver
    global Result

    n = random.randint(1, 100)
    if n <= 20:
        AIGoodPlay()
    else:
        AIBadPlay()
    
    if len(rc_list) == 0:
        GameOver = True
        if AIScore > PlayerScore:
            Result = "AI Win"
        elif AIScore < PlayerScore:
            Result = "Player Win"
        else:
            Result = "Draw"

def PlayerPlay(x, y):
    gx = x // unit
    gy = y // unit
    global PlayerScore

    for rc in rc_list:
        if rc.IsMe(gx, gy) == True:
            PlayerScore += rc.GetScore()
            rc_list.remove(rc)
            return True

    return False

def on_key_down(key):
    if key == keys.ESCAPE:
        quit()

def on_mouse_down(pos):
    if GameOver == True:
        return

    x = pos[0]
    y = pos[1]
    
    flag = PlayerPlay(x, y)
    if flag == True:
        AIPlay()



def draw():
    global GameOver
    screen.clear()
    screen.fill(BACK_COLOR)
    for rc in rc_list:
        rc.Draw()

    screen.draw.text("AI Score: " + str(AIScore), topleft = (410, 200))
    screen.draw.text("Player Score: " + str(PlayerScore), topleft = (410, 300))
    
    if GameOver == True:
        screen.draw.text("GameOver - " + Result, topleft = (410, 100))


